# coding: UTF-8
# Filename : chain_commentlist_api.py
# Company : imedia
# Author : rose # -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils,const,xml_tpl, err_tpl
import chain_commentlist_data_model
import time
'''
http://api.imedia.com/app/part/list
'''
		
#details list
def chain_commentlist_list(request):
    #record log((frist action))
    httputils.footprint(request)
    #param
    cus_id = httputils.post(request, 'cus_id')#is customer id,more
    size = httputils.post(request, 'size')
    pagenum = httputils.post(request, 'pagenum')
    if not utils.is_num(size): size = 5
    if not utils.is_num(pagenum): pagenum = 1
    if not utils.is_num(cus_id): cus_id = 1 
    #Verification
    output = chain_commentlist_data_model.imedia_start 
    output += get_body_str(cus_id, size, pagenum)
    output += chain_commentlist_data_model.imedia_end
    return response(output) 
#获取中间数据体
def get_body_str(cus_id, size, pagenum):
    #sql
    sql = '''
    select a.`id`, user_id, score, created_at, content,cus_name
    from chain_comment as a , customer as b 
    where cus_id=%s and reply_id = 0 and  a.cus_id = b.id
    limit %s, %s
    '''
    #获取起始行
    start_row = utils.get_star_row(size, pagenum)
    param = [int(cus_id), start_row, int(size)]
    rsts = mysql.doSearch(sql, param)
    body_str = ''
    i = 0
    for obj in rsts:
        i = i + 1
        body_template = chain_commentlist_data_model.imedia_body
        body_template = body_template.replace('{id}', str(obj[0]))
        body_template = body_template.replace('{user}', str(obj[5]))
        body_template = body_template.replace('{score}', str(obj[2]))
        ISOTIMEFORMAT='%Y-%m-%d_%X'
        start_time = time.strftime(ISOTIMEFORMAT,time.localtime(obj[3]))
        body_template = body_template.replace('{datetime}', start_time)
        body_template = body_template.replace('{content}', str(obj[4]))
        body_template += get_replay_str(int(cus_id)) 
        body_str += body_template
        body_str += chain_commentlist_data_model.imedia_body_end
    #body_str = body_str[0:-10] 
    return body_str

def get_replay_str(cus_id): 
    #sql
    sql = '''
    select created_at, content
    from chain_comment 
    where cus_id=%s and reply_id <> 0
    '''
    #获取起始行
    #start_row = utils.get_star_row(size, pagenum)
    param = [int(cus_id)]
    rsts = mysql.doSearch(sql, param)
    body_str = ''
    for obj in rsts:
        body_template = chain_commentlist_data_model.imedia_body_reply
        body_template = body_template.lstrip()
        ISOTIMEFORMAT='%Y-%m-%d_%X'
        start_time = time.strftime(ISOTIMEFORMAT,time.localtime(obj[0]))
        body_template = body_template.replace('{datetime}', start_time)
        body_template = body_template.replace('{content}', str(obj[1]))
        body_str += body_template 
    return body_str   
     


